/*
 * Copyright (c) 2023-2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define API __attribute__((visibility("default")))

#include "peripheral_notification.h"
#include "edm_errors.h"
#include "file_ex.h"
#include "hilog_wrapper.h"
#include "locale_config.h"
#include "locale_info.h"
#include "notification_helper.h"
#include "notification_locale.h"
#include "os_account_manager.h"
#include "securec.h"
#include "want_agent_helper.h"
#include "want_agent_info.h"
#include <cJSON.h>
#include <map>

namespace OHOS {
namespace ExternalDeviceManager {
static const std::string ENTITIES = "entity.system.browsable";
static const std::string ACTION = "ohos.want.action.viewData";

DeviceNotification &DeviceNotification::GetInstance()
{
    static DeviceNotification instance;
    return instance;
}

void DeviceNotification::HandleNotification(FaultInfo &faultInfo)
{
    NotificationLocale::GetInstance().SetLanguage("zh_CN"); // ��ʱ�����Ͽ�ǰ��Ҫɾ��
    NotificationLocale::GetInstance().ParseLocaleCfg();
    NotificationLocale::GetInstance().UpdateStringMap();
    if (faultInfo.title.empty() || faultInfo.msg.empty()) {
        EDM_LOGE(MODULE_SERVICE, "Invalid notification: missing title or message");
        return;
    }
    FaultInfo notifCfg = FillNotificationotifCfg(faultInfo);
    PeripheralDeviceNotification(notifCfg);
}

static bool SetTitleAndText(
    std::shared_ptr<Notification::NotificationNormalContent> content, const std::string &title, const std::string &text)
{
    if (content == nullptr) {
        EDM_LOGE(MODULE_SERVICE, "notification normal content nullptr");
        return false;
    }

    content->SetTitle(title);
    content->SetText(text);
    return true;
}

static void SetBasicOption(Notification::NotificationRequest &request)
{
    request.SetCreatorUid(NOTIFICATION_SERVICE_SYS_ABILITY_ID);
    int32_t userId = 0;
    AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(NOTIFICATION_SERVICE_SYS_ABILITY_ID, userId);
    request.SetCreatorPid(getpid());
    request.SetCreatorUserId(userId);
    request.SetInProgress(true);
    request.SetUnremovable(true);
    request.SetTapDismissed(true);
    request.SetSlotType(OHOS::Notification::NotificationConstant::SlotType::SOCIAL_COMMUNICATION);
    request.SetNotificationControlFlags(AIVNSN_NOTIFICATION_CONTROL_FLAG);
}

static void SetWantAgent(OHOS::Notification::NotificationRequest &request, const std::string &uri)
{
    EDM_LOGI(MODULE_SERVICE, "SetWantAgent Start");
    auto want = std::make_shared<AAFwk::Want>();
    want->SetAction(ACTION);
    want->SetUri(uri);
    want->AddEntity(ENTITIES);
    std::vector<std::shared_ptr<AAFwk::Want>> wants;
    wants.push_back(want);

    std::vector<AbilityRuntime::WantAgent::WantAgentConstant::Flags> flags;
    flags.push_back(AbilityRuntime::WantAgent::WantAgentConstant::Flags::CONSTANT_FLAG);

    AbilityRuntime::WantAgent::WantAgentInfo wantAgentInfo(
        0, AbilityRuntime::WantAgent::WantAgentConstant::OperationType::START_ABILITY, flags, wants, nullptr);
    auto wantAgent = AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo);
    request.SetWantAgent(wantAgent);
}

void DeviceNotification::GetPixelMap(const std::string &path)
{
    if (iconPixelMap_ != nullptr) {
        EDM_LOGE(MODULE_DEV_MGR, "peripheral icon pixel map already exists.");
        return;
    }

    if (!std::filesystem::exists(path)) {
        EDM_LOGE(MODULE_DEV_MGR, "peripheral icon file path not exists.");
        iconPixelMap_ = nullptr;
        return;
    }
    uint32_t errorCode = 0;
    Media::SourceOptions opts;
    opts.formatHint = "image/png";
    std::unique_ptr<Media::ImageSource> imageSource = Media::ImageSource::CreateImageSource(path, opts, errorCode);
    if (imageSource == nullptr) {
        EDM_LOGE(MODULE_DEV_MGR, "imageSource nullptr");
        iconPixelMap_ = nullptr;
        return;
    }
    Media::DecodeOptions decodeOpts;
    std::unique_ptr<Media::PixelMap> pixelMap = imageSource->CreatePixelMap(decodeOpts, errorCode);
    iconPixelMap_ = std::move(pixelMap);
}

FaultInfo DeviceNotification::FillNotificationotifCfg(const FaultInfo &faultInfo)
{
    auto &localeConfig = NotificationLocale::GetInstance();
    FaultInfo temp;

    temp.title = localeConfig.GetStringByKey(faultInfo.title);
    temp.msg = localeConfig.GetStringByKey(faultInfo.msg);
    temp.uri = faultInfo.uri;
    return temp;
}

void DeviceNotification::PeripheralDeviceNotification(FaultInfo &faultInfo)
{
    EDM_LOGI(MODULE_SERVICE, "Satrt PeripheralDeviceNotification %{public}s", faultInfo.GetInfo().c_str());
    std::shared_ptr<Notification::NotificationNormalContent> content =
        std::make_shared<Notification::NotificationNormalContent>();
    if (content == nullptr) {
        EDM_LOGE(MODULE_SERVICE, "Failed to create NotificationNormalContent");
        return;
    }

    if (!SetTitleAndText(content, faultInfo.title, faultInfo.msg)) {
        EDM_LOGE(MODULE_SERVICE, "error setting title and text");
        return;
    }

    std::shared_ptr<Notification::NotificationContent> notificationContent =
        std::make_shared<Notification::NotificationContent>(content);
    if (notificationContent == nullptr) {
        EDM_LOGE(MODULE_SERVICE, "Failed to create NotificationContent");
        return;
    }

    int32_t notificationId = static_cast<int32_t>(std::hash<std::string>()(faultInfo.title));
    EDM_LOGI(MODULE_SERVICE, "SetNotificationId notifationId[%{public}d]", notificationId);
    Notification::NotificationRequest request(notificationId);
    request.SetContent(notificationContent);

    SetBasicOption(request);

    GetPixelMap(PERIPHERAL_ICON_PATH);
    if (iconPixelMap_ != nullptr) {
        request.SetLittleIcon(iconPixelMap_);
        request.SetBadgeIconStyle(Notification::NotificationRequest::BadgeStyle::LITTLE);
    }

    SetWantAgent(request, faultInfo.uri);

    int ret = Notification::NotificationHelper::PublishNotification(request);
    EDM_LOGI(MODULE_SERVICE, "peripheral service publish notification result = %{public}d", ret);
}

extern "C" API void HandleNotification(FaultInfo &faultInfo)
{
    DeviceNotification::GetInstance().HandleNotification(faultInfo);
}
} // namespace ExternalDeviceManager
} // namespace OHOS